package com.easysoft.commons.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class UpdateUtils {
    public static String savePicture(MultipartFile multipartFile, String categoryId, HttpServletRequest request) {
        // 判段是否图片
        InputStream in = null;
        Boolean isPicture = false;
        if (multipartFile != null && !("").equals(multipartFile)) {
            try {
                in = multipartFile.getInputStream();
                isPicture = CheckFile.isPicture(in);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            if (isPicture) {
                String currNum = String.valueOf(System.currentTimeMillis());
                return uploadImg(request, categoryId, multipartFile, currNum);
            }
        }
        return null;
    }

    public static String uploadImg(HttpServletRequest request, String type, MultipartFile sourceFile, String currNum) {
        if (!sourceFile.isEmpty()) {
            // 文件保存目录路径
            String savePath = request.getSession().getServletContext().getRealPath("/") + "/images/list" + type + "/";
            String saveUrl = request.getContextPath() + "/images/list" + type + "/";
            // 目录不存在则创建
            File uploadPath = new File(savePath);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            String fileName = sourceFile.getOriginalFilename();
            String dir = fileName.substring(fileName.indexOf("."), fileName.length());
            fileName = currNum + dir;
            try {
                // 文件保存路径
                String filePath = savePath + fileName;
                // 转存文件
                sourceFile.transferTo(new File(filePath));
                return saveUrl + fileName;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
}
